package com.ziq.zcamp.util

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import com.ziq.zcamp.R
import com.ziq.zcamp.main.MainActivity
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.MerchantManager
import com.ziq.zcamp.manager.UserManager
import me.leolin.shortcutbadger.ShortcutBadger
import java.util.*


object BadgeUtil {

    fun showBadgeNum(){
        try {
            GlobalContextManager.appContext?.let {
                var total = 0
                total += getMsgCount()
                //不显示用户订单相关的
//                total += UserManager.instance.getUserOrderBadgeNum()
                total += MerchantManager.instance.getBadgeNum()
                setBadgeNum(it, total)
            }
        }catch (e:Exception){}
    }

    var lastNum = 0

    fun setBadgeNum(context: Context, num: Int){
        try {
            if(Build.MANUFACTURER.equals("Xiaomi", ignoreCase = true) || OSHelper.isMiUI()){
                if(num > 0 && lastNum != num){
                    lastNum = num
                    setXiaoMiBadgeNum(context, num)
                }
            } else if(OSHelper.isEmUI()){
                setHuaWeiBadgeNum(context, num)
            } else {
                if(num > 0){
                    val result = ShortcutBadger.applyCount(context, num)
                    if(!result){
                        setXiaoMiBadgeNum(context, num)
                    }
                }else {
                    ShortcutBadger.removeCount(context)
                }
            }
        }catch (e:Exception){}
    }

    fun getMsgCount():Int{
        val newFansCount = UserManager.instance.newFansCountForMsgCenter.value?:0
        val praiseCount = UserManager.instance.praiseCountForMsgCenter.value?:0
        val commentCount = UserManager.instance.commentCountForMsgCenter.value?:0
        val sessionCount = UserManager.instance.userMessageSessionList.value?.count?:0
        var imCount = 0
        try {
            if(UserManager.instance.imConf.value?.open_im == true){
//                imCount = JMessageClient.getAllUnReadMsgCount()
                if(imCount < 0){
                    imCount = 0
                }
            }
        }catch (e:Exception){}

        var total = newFansCount + praiseCount + commentCount + sessionCount + imCount
        return total
    }


    private fun isXiaoMi(context: Context): Boolean {
        val intent = Intent(Intent.ACTION_MAIN)
        intent.addCategory(Intent.CATEGORY_HOME)
        val resolveInfos = context.packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
        for (resolveInfo in resolveInfos) {
            val currentHomePackage = resolveInfo.activityInfo.packageName
            if (getXiaoMiLaunchers().contains(currentHomePackage)) {
                return true
            }
        }
        return false
    }


    private fun getXiaoMiLaunchers(): List<String> {
        return Arrays.asList(
            "com.miui.miuilite",
            "com.miui.home",
            "com.miui.miuihome",
            "com.miui.miuihome2",
            "com.miui.mihome",
            "com.miui.mihome2",
            "com.i.miui.launcher"
        )
    }

    private fun setXiaoMiBadgeNum(context: Context, num: Int) {
        try {
            val notificationManager =
                context.getSystemService(AppCompatActivity.NOTIFICATION_SERVICE) as NotificationManager
            val title = "消息提示"
            val desc = "您有" + num + "条未读消息"
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val channelId = "default"
                val channelName = "默认通知"
                val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT)
                channel.setShowBadge(true)
                notificationManager.createNotificationChannel(channel)
            }
            val intent = Intent(context, MainActivity::class.java)
            intent.setAction("android.intent.action.MAIN")
            intent.addCategory("android.intent.category.LAUNCHER")
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            val pendingIntent = PendingIntent.getActivity(context, 0, intent, 0)
            val notification: Notification = NotificationCompat.Builder(context, "default")
                .setContentTitle(title)
                .setContentText(desc)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setAutoCancel(true)
                .setChannelId("default")
                .setNumber(num)
                .setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL)
                .setContentIntent(pendingIntent)
                .build()

            //取消掉上一条通知消息
//            notificationManager.cancel(1)
            try {
                val field = notification.javaClass.getDeclaredField("extraNotification")
                val extraNotification = field[notification]
                val method = extraNotification.javaClass.getDeclaredMethod(
                    "setMessageCount",
                    Int::class.javaPrimitiveType
                )
                method.isAccessible = true
                method.invoke(extraNotification, num)
            }catch (e:Exception){}

            notificationManager.notify(1, notification)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun setHuaWeiBadgeNum(context: Context, num: Int)
    {
        try {
            val bunlde = Bundle()
            bunlde.putString("package", context.packageName)
            //此处为启动页路径
            bunlde.putString("class", "com.gmlive.camp.business.main.FirstScreenActivity")
            bunlde.putInt("badgenumber", num)
            context.contentResolver.call(
                Uri.parse("content://com.huawei.android.launcher.settings/badge/"),
                "change_badge",
                null,
                bunlde
            )
        } catch (e:Exception) {
            e.printStackTrace()
        }
    }


}